/**
 *    Copyright 2009-2020 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.aapl.interceptor;

import org.apache.ibatis.aapl.reflect.MetaUtils;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.executor.statement.RoutingStatementHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.scripting.defaults.DefaultParameterHandler;

import java.util.List;

/**
 * 修改参数后，调用该处理器的方法可以重新生成MyBatis语句。
 *
 * @author gu
 * @date 2020/6/8 13:38
 */
public class RefreshStatementProcessor implements StatementProcessor {

  @Override
  public void process(StatementHandler handler) {
    if (!(handler instanceof RoutingStatementHandler)) {
      return;
    }

    RoutingStatementHandler routingStatementHandler = ((RoutingStatementHandler) handler);
    BoundSql boundSql = routingStatementHandler.getBoundSql();
    ParameterHandler parameterHandler = routingStatementHandler.getParameterHandler();
    if (parameterHandler instanceof DefaultParameterHandler) {
      DefaultParameterHandler h = ((DefaultParameterHandler) parameterHandler);
      MetaObject metaObject = MetaUtils.getMetaObject(h);
      MappedStatement statement =(MappedStatement) metaObject.getValue("mappedStatement");
      Object param = parameterHandler.getParameterObject();
      BoundSql bs = statement.getBoundSql(param);
      String sql = bs.getSql();
      metaObject = MetaUtils.getMetaObject(boundSql);
      List<ParameterMapping> parameterMappings = bs.getParameterMappings();
      metaObject.setValue("sql",sql);
      metaObject.setValue("parameterMappings",parameterMappings);
    }
  }
}
